﻿using Jsbeautifier;
using jsxbin_to_jsx.JsxbinDecoding;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace jsxbin_to_jsx_GUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(DataFormats.FileDrop) != null)
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            String[] fileNames = (String[])e.Data.GetData(DataFormats.FileDrop);
            for (int i = 0; i < fileNames.Length; i++)
            {
                var f = fileNames[i];
                AddFile(f);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem l in listView1.Items)
            {
                string f = l.SubItems[1].Text;
                string jsxbin = File.ReadAllText(f, Encoding.ASCII);
                string jsx = AbstractNode.Decode(jsxbin, true);
                jsx = new Beautifier().Beautify(jsx);
                string of = Path.GetDirectoryName(f) + "\\" + Path.GetFileNameWithoutExtension(f) + ".jsx";
                File.WriteAllText(of, jsx, Encoding.UTF8);
                l.SubItems[2].Text = "已解密";
            }
        }

        private void AddFile(string f)
        {
            if (Path.GetExtension(f) != ".jsxbin")
                return;
            ListViewItem lvi = new ListViewItem(Path.GetFileNameWithoutExtension(f));
            lvi.SubItems.Add(f);
            lvi.SubItems.Add("未解密");
            listView1.Items.Add(lvi);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach(var f in openFileDialog1.FileNames)
                {
                    AddFile(f);
                }
            }
        }
    }
}
